package com.yonyou.brigade.third_parties.yihao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xiaoleilu.hutool.util.IdcardUtil;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.props.PropUtil;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.order_center.model.ThirdResult;
import com.yonyou.brigade.third_parties.yihao.constants.YihaoConstants;
import com.yonyou.brigade.third_parties.yihao.dao.YihaoUserMapper;
import com.yonyou.brigade.third_parties.yihao.model.YihaoUser;
import com.yonyou.brigade.third_parties.yihao.service.ICLYHPublicService;
import com.yonyou.brigade.third_parties.yihao.service.ICLYHUserService;
import com.yonyou.brigade.third_parties.yihao.service.IYihaoDeptService;
import com.yonyou.brigade.order_center.util.YHUtils;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2018/10/15.
 */
@Service
public class CLYHUserServiceImpl extends ServiceImpl<YihaoUserMapper, YihaoUser> implements ICLYHUserService {

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;


    @Autowired
    @Qualifier("CLYHPublicServiceImpl")
    private ICLYHPublicService iclyhPublicService;

    @Autowired
    private PropUtil propUtil;

    @Autowired
    private YHUtils yhUtils;

    @Autowired
    private IYihaoDeptService yihaoDeptService;

    private Logger logger= LoggerFactory.getLogger(this.getClass());

    private String CompareProperties = "empID,gender,email,name,phone,outDeptNO,deptName,postName,postPk";


    @Override
    public String loginUrl(String tenant, String org, String phone, String pageType, String pcOrH5, String jsonExt) {
        String resultUrl = "";
        BriChannel briChannel = briChannelService.getEnableInfoByTenantOrg(tenant,org,"clyh");
        if(briChannel==null) {
            //没有开通差旅壹号
            resultUrl = propUtil.getNO_ACCESS_URL();
            return resultUrl;
        }else {
            JSONObject config = JSONObject.parseObject(briChannel.getConfig());
            UcUserDto userDto = iUserCenterService.getCompleteUcUserDtoByPhone(phone, tenant);
            if (userDto != null){
                JSONObject jsonObject= JSON.parseObject(briChannel.getConfig());
                jsonObject.put("tenant",tenant);
                //绿城租户使用身份证号进行单点，其他租户用员工编号
                String rsUrl = "";
                if ("x0tc1f2v".equals(tenant)) {
                    rsUrl = iclyhPublicService.ssoLogin(userDto.getPassengerId(),jsonObject,pcOrH5);
                } else {
                    if (BriChannel.SYNCORGDEPT == briChannel.getSyncOrgDept()) {
                        //同步一级部门
                        yihaoDeptService.sysOrgDept(tenant,userDto.getOrgPk(), userDto.getOrgName(), config);
                        //同步该用户的部门信息
                        yihaoDeptService.sysUserDept(tenant, phone, briChannel);
                    }
                    if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                        //单点登录前向同步用户
                        sysYiHaoUser(tenant, phone, briChannel);
                    }
                    rsUrl = iclyhPublicService.ssoLogin(userDto.getPersonCode(),jsonObject,pcOrH5);
                }
//                String rsUrl = iclyhPublicService.ssoLogin(phone,jsonObject,pcOrH5);
                if (!StringUtils.isEmpty(rsUrl)){
                    logger.info("差旅单点url ：" + rsUrl);
                    resultUrl = rsUrl;
                }else {
                    resultUrl = propUtil.getNO_ACCESS_URL();
                }
            }else {
                //没有查询到用户信息
                logger.info("查询用户为空! 手机号：" + phone);
                resultUrl = propUtil.getNO_ACCESS_URL();
            }
        }

        return resultUrl;
    }


    @Override
    public void sysClyhUsers(String tenant, String orgPk, List<UcUserDto> ucUserDtos, BriChannel briChannel) {
        for (UcUserDto ucUserDto : ucUserDtos) {
            sysYiHaoUser(tenant, ucUserDto.getPhone(), briChannel);
        }
    }

    /**
     * 同步用户
     * @param tenant
     * @param phone
     * @param briChannel
     */
    @Override
    public void sysYiHaoUser(String tenant, String phone, BriChannel briChannel){

        Wrapper<YihaoUser> wrapper = new EntityWrapper<>();
        wrapper.eq("tenantId",tenant);
        wrapper.eq("phone", phone);
        List<YihaoUser> yihaoUserList = this.baseMapper.selectList(wrapper);

        UcUserDto userDto = iUserCenterService.getCompleteUcUserDtoByPhone(phone, tenant);
        if (userDto == null){
            return;
        }
        YihaoUser yihaoUser = getYiHaoUser(new YihaoUser(), userDto, tenant, briChannel);
        logger.info("开始同步用户到差旅壹号");
        //同步
        if (yihaoUserList.size() == 0){
            yihaoUserList.add(yihaoUser);
            ThirdResult thirdResult = iclyhPublicService.sysUserToClyh(userDto, yihaoUserList, tenant, briChannel, YihaoConstants.SYS_TYPE_ADD);
            if (thirdResult.getSuccess()){
                this.baseMapper.insert(yihaoUser);
            }
        }else{
            //如果已经同步过，检查信息是否有变化，如果有变化则更新
            Map<String, String> compareMap = new HashMap<>();
            String[] compareFields = CompareProperties.split(",");
            Map<String, Object> compareResult = yhUtils.compareFields(compareFields, compareMap, yihaoUserList.get(0), yihaoUser);
            if (compareResult != null && compareResult.size() > 0) {
                //更新已经同步过的用户信息
                List<YihaoUser> list = new ArrayList<>();
                yihaoUser.setEmpID(yihaoUserList.get(0).getEmpID());
                list.add(yihaoUser);
                ThirdResult thirdResult = iclyhPublicService.sysUserToClyh(userDto, list, tenant, briChannel, YihaoConstants.SYS_TYPE_EDIT);
                yihaoUser.setId(yihaoUserList.get(0).getId());
                this.baseMapper.updateById(yihaoUser);
            }
        }
    }

    @Override
    public void quitStaff(String tenantId, String orgPk, List<String> userIdList, BriChannel briChannel) {
        List<UcUserDto> ucUserDtoList = iUserCenterService.getCompleteUcUserDtoByUserid(userIdList, tenantId);
        if (ucUserDtoList != null && ucUserDtoList.size() > 0){
            List<YihaoUser> list = new ArrayList<>();
            List<String> phoneList = new ArrayList<>();
            for (UcUserDto ucUserDto : ucUserDtoList) {
                list.add(getYiHaoUser(new YihaoUser(), ucUserDto, tenantId, briChannel));
                phoneList.add(ucUserDto.getPhone());
            }
            //员工离职
            iclyhPublicService.sysUserToClyh(new UcUserDto(), list, tenantId, briChannel, YihaoConstants.SYS_TYPE_QUIT);
            //删除同步记录
            Wrapper<YihaoUser> wrapper = new EntityWrapper<>();
            wrapper.eq(YihaoUser.TENANTID, tenantId);
            wrapper.in(YihaoUser.PHONE, phoneList);
            this.delete(wrapper);

        }
    }

    @Override
    public void disableUserByOrg(String tenantId, String orgPk, BriChannel briChannel){
        logger.info("租户：" + tenantId + "组织：" + orgPk + " 开始禁用差旅壹号员工");
        Wrapper<YihaoUser> wrapper = new EntityWrapper<>();
        wrapper.eq(YihaoUser.TENANTID, tenantId);
        wrapper.eq(YihaoUser.ORGPK, orgPk);
        List<YihaoUser> yihaoUserList = this.selectList(wrapper);
        //员工离职
        iclyhPublicService.sysUserToClyh(new UcUserDto(), yihaoUserList, tenantId, briChannel, YihaoConstants.SYS_TYPE_DISABLE);
        this.delete(wrapper);
        logger.info("禁用差旅壹号员工结束");
    }


    /**
     * 从用户中心用户获取差旅一号用户
     * @param yihaoUser
     * @param ucUserDto
     * @param tenant
     * @return
     */
    private YihaoUser getYiHaoUser(YihaoUser yihaoUser, UcUserDto ucUserDto, String tenant, BriChannel briChannel){
        yihaoUser.setPhone(ucUserDto.getPhone());
        yihaoUser.setName(ucUserDto.getUserName());
        yihaoUser.setEmpID(ucUserDto.getPersonCode());
        yihaoUser.setEmail(ucUserDto.getEmail());
        yihaoUser.setBirthDay(ucUserDto.getBirthday());
        yihaoUser.setOrgPk(ucUserDto.getOrgPk());
        try{
            yihaoUser.setGender(IdcardUtil.getGenderByIdCard(ucUserDto.getPassengerId()));
        }catch (Exception e){
            logger.error("根据身份证获取性别异常，身份证号：" + ucUserDto.getPassengerId() );
        }
        yihaoUser.setTenantId(tenant);
        // 如果不同步部门时，需将顶级部门作为人员的部门同步
        if (BriChannel.SYNCORGDEPT == briChannel.getSyncOrgDept()) {
            yihaoUser.setDeptName(ucUserDto.getDeptName());
            yihaoUser.setOutDeptNO(ucUserDto.getDeptPk());
        } else {
            String config = briChannel.getConfig();
            if (!StringUtils.isEmpty(config)) {
                JSONObject configJSON = JSONObject.parseObject(config);
                yihaoUser.setOutDeptNO(configJSON.getString("superDeptNO"));
            }
        }
        if (0 != briChannel.getSyncRank()) {
            yihaoUser.setPostName(ucUserDto.getPostName());
            yihaoUser.setPostPk(ucUserDto.getPostPk());
        }

        return yihaoUser;
    }
}